/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.bsplus.domain;

import java.io.Serializable;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

@MappedSuperclass
public abstract class AbstractEntity implements Serializable,
		Comparable<AbstractEntity>
{
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;

	public Long getId()
	{
		return id;
	}

	public void setId(Long id)
	{
		this.id = id;
	}

	@Override
	public boolean equals(Object obj)
	{
		if (getId() == null)
		{
			return super.equals(obj);
		}
		else
		{
			if (!(obj instanceof AbstractEntity))
			{
				return false;
			}
			if (this == obj)
			{
				return true;
			}
			AbstractEntity entity = (AbstractEntity) obj;
			return new EqualsBuilder().append(getId(), entity.getId())
					.isEquals();
		}
	}

	@Override
	public int hashCode()
	{
		return new HashCodeBuilder().append(getId()).toHashCode();
	}

	/**
	 * Check if the entity exists already
	 * 
	 * @return true if this entity exists on the database (id != null)
	 */
	public boolean isPersisted()
	{
		return getId() != null;
	}

	@Override
	public String toString()
	{
		return getClass().getName() + " id=" + id;
	}

	@Override
	public int compareTo(AbstractEntity obj)
	{
		if (getId() == null || obj.getId() == null)
		{
			return CompareToBuilder.reflectionCompare(this, obj);
		}
		else
		{
			return new CompareToBuilder().append(getId(), obj.getId())
					.toComparison();
		}
	}
}
